package com.qfhd.soft.cjzcore.UI.Core;

import android.Manifest;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;

import androidx.appcompat.app.AlertDialog;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;
import androidx.core.os.EnvironmentCompat;


import com.qfhd.soft.cjzcore.Core.CJFile;
import com.qfhd.soft.cjzcore.Core.CJLogger;
import com.qfhd.soft.cjzcore.R;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class CJCameraHelper {

    private String mPhtotPath;
    private Uri uriImage;
    private File mPhotoFile = null;
    private Context mContext;
    private Activity mActivity;

    // 是否是Android 10以上手机
    private boolean isAndroidQ = Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q;

    private static CJCameraHelper cameraHelper;

    public static CJCameraHelper getInstance() {
        if (cameraHelper == null) {
            synchronized (CJCameraHelper.class) {
                cameraHelper = new CJCameraHelper();
            }
        }
        return cameraHelper;
    }

    public String getmPhtotPath() {
        return mPhtotPath;
    }

    public File getmPhotoFile() {
        return mPhotoFile;
    }

    public Uri getUriImage() {
        return uriImage;
    }

    //选择图片 //需要重写onActivityResult
    public void selectPic(Context context, Activity activity) {
        mContext = context;
        mActivity = activity;

        //动态请求权限，除此之外还需进行Androidmanifest.xml中进行请求
        if (ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA)
                != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(context,
                Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(context,
                Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(activity,
                    new String[]{Manifest.permission.CAMERA,
                            Manifest.permission.READ_EXTERNAL_STORAGE,
                            Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    1);
        }

        final CharSequence[] items = {"相册", "拍照"};
        AlertDialog.Builder dlg = new AlertDialog.Builder(context);
        dlg.setTitle("添加图片");
        dlg.setItems(items, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int item) {
                // 这里item是根据选择的方式，
                if (item == 0) {
                    //相册
                    /**19之后的系统相册的图片都存在于MediaStore数据库中；19之前的系统相册中可能包含不存在与数据库中的图片，所以如果是19之上的系统
                     * 跳转到19之前的系统相册选择了一张不存在与数据库中的图片，解析uri时就可能会出现null*/
                    Intent intent = new Intent();
                    if (Build.VERSION.SDK_INT < 19) {
                        intent.setAction(Intent.ACTION_GET_CONTENT);
                        intent.setType("image/*");
                    } else {
                        intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,"image/*");
                    }
                    activity.startActivityForResult(intent, 0);
                } else {
                    //拍照
                    Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    // 判断是否有相机
                    if (captureIntent.resolveActivity(mContext.getPackageManager()) != null) {
                        File photoFile = null;
                        Uri photoUri = null;

                        if (isAndroidQ) {
                            // 适配android 10
                            photoUri = createImageUri();
                            uriImage = photoUri;
                        } else {
                            try {
                                photoFile = createImageFile();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }

                            if (photoFile != null) {
                                mPhtotPath = photoFile.getAbsolutePath();
                                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                                    //适配Android 7.0文件权限，通过FileProvider创建一个content类型的Uri
                                    photoUri = FileProvider.getUriForFile(mContext, context.getResources().getString(R.string.app_fileProvider), photoFile);
                                    uriImage = photoUri;
                                } else {
                                    photoUri = Uri.fromFile(photoFile);
                                    uriImage = photoUri;
                                }
                            }
                        }

                        photoUri = photoUri;
                        if (photoUri != null) {
                            captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
                            captureIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
                            mActivity.startActivityForResult(captureIntent, 1);
                        }
                    }
                }
            }
        }).create();
        dlg.show();

    }

    /**
     * 创建图片地址uri,用于保存拍照后的照片 Android 10以后使用这种方法
     */
    private Uri createImageUri() {
        String status = Environment.getExternalStorageState();
        // 判断是否有SD卡,优先使用SD卡存储,当没有SD卡时使用手机存储
        if (status.equals(Environment.MEDIA_MOUNTED)) {
            return mContext.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new ContentValues());
        } else {
            return mContext.getContentResolver().insert(MediaStore.Images.Media.INTERNAL_CONTENT_URI, new ContentValues());
        }
    }

    /**
     * 创建保存图片的文件
     */
    private File createImageFile() throws IOException {
        String imageName = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
//        File storageDir = mContext.getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        File storageDir = new File(CJFile.getInstance().getDataFolder());
        if (!storageDir.exists()) {
            storageDir.mkdir();
        }
        File tempFile = new File(storageDir, imageName);
        if (!tempFile.exists()) {
            tempFile.createNewFile();
        }
        return tempFile;
    }

    private String getPhotoFileName() {
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat dateFormat = new SimpleDateFormat("'IMG'_yyyyMMdd_HHmmss");
        return dateFormat.format(date) + ".png";
    }

    //将Uri图片类型转换成File，BitMap类型
    //在界面上显示BitMap图片，以防止内存溢出
    //上传可选择File文件上传

    public String getFilePath(Uri uriImage, int type, Context context) {
        Bitmap photoBmp = null;
        if (uriImage != null) {
            try {
//                photoBmp = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uriImage);
//                ByteArrayOutputStream fos = new ByteArrayOutputStream();
//                photoBmp.compress(Bitmap.CompressFormat.JPEG, 80, fos);
                //以上代码压缩不行，还是会造成内存溢出

                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inSampleSize = 2; //图片宽高都为原来的二分之一，即图片为原来的四分之一
                photoBmp = BitmapFactory.decodeStream(context.getContentResolver()
                        .openInputStream(uriImage), null, options);

                String path = "";
                if (type == 0) {
//                    file = new File();
                    path = CJFile.getPathByUri(mActivity, uriImage);

                } else {
                    if (mPhotoFile != null) {
                        path = mPhtotPath;
                    }

                }
                return path;

            } catch (IOException e) {
                e.printStackTrace();
                CJLogger.v("saveUritoFile: ---------压缩图片异常！");
            }
        }
        return null;
    }
}
